<template>
  <div class="choose-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.courseName" placeholder="课程关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.major" placeholder="专业关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.className" placeholder="班级关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading" size="small">
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" fixed="left" />
        <el-table-column prop="course_name" label="课程名称" :min-width="220" show-overflow-tooltip />
        <el-table-column prop="student_name" label="学生姓名" width="120" />
        <el-table-column prop="class_name" label="班级名称" :min-width="180" show-overflow-tooltip />
        <el-table-column prop="major_name" label="专业名称" :min-width="180" show-overflow-tooltip />
          <el-table-column prop="sc_daily_score" label="日常分" width="90" align="center">
            <template #default="{ row }">
              <span class="badge" :class="badgeByScore(row.sc_daily_score)">{{ row.sc_daily_score ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sc_exam_score" label="期末分" width="90" align="center">
            <template #default="{ row }">
              <span class="badge" :class="badgeByScore(row.sc_exam_score)">{{ row.sc_exam_score ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sc_score" label="总分" width="90" align="center">
            <template #default="{ row }">
              <span class="badge" :class="badgeByScore(row.sc_score)">{{ row.sc_score ?? '-' }}</span>
            </template>
          </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          size="small"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增选课对话框 -->
    <el-dialog v-model="dialogVisible" title="新增选课" width="420px" class="form-dialog" modal-class="light-modal-mask">
      <el-form :model="dialogForm" label-width="80px" size="small">
        <el-form-item label="课程">
          <el-select v-model="dialogForm.sc_course_id" filterable remote :remote-method="remoteCourse" placeholder="搜索课程">
            <el-option v-for="c in courseList" :key="c.course_id" :label="c.course_name" :value="c.course_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="学生">
          <el-select v-model="dialogForm.sc_student_id" filterable remote :remote-method="remoteStudent" placeholder="搜索学生">
            <el-option v-for="s in studentList" :key="s.student_id" :label="`${s.student_name}（${s.class_name || ''}）`" :value="s.student_id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getChooseAPI, addChooseAPI } from '@/api/admin/choose.js'
import { getCourseAPI } from '@/api/admin/course.js'
import { getStudentAPI } from '@/api/admin/student.js'

// 搜索表单
const searchForm = reactive({
  courseName: '',
  major: '',
  className: ''
})

// 表格数据
const tableData = ref([])

// 加载态
const loading = ref(false)

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 获取选课数据
const fetchChooseData = async () => {
  loading.value = true
  const params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  try {
    const res = await getChooseAPI(params)
    tableData.value = res.list || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

onMounted(fetchChooseData)

// 序号（跨页连续）
const indexMethod = (index) => {
  return (pagination.pageNo - 1) * pagination.pageSize + index + 1
}

// 分数段徽章颜色：<60 红，60-79 橙，>=80 绿；空值用灰
const badgeByScore = (val) => {
  if (val === null || val === undefined || val === '') return 'badge--gray'
  const n = Number(val)
  if (Number.isNaN(n)) return 'badge--gray'
  if (n < 60) return 'badge--red'
  if (n < 80) return 'badge--orange'
  return 'badge--green'
}


// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchChooseData()
}

// 重置
const handleReset = () => {
  searchForm.courseName = ''
  searchForm.major = ''
  searchForm.className = ''
  pagination.pageNo = 1
  pagination.pageSize = 10
  fetchChooseData()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchChooseData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchChooseData()
}

// 新增相关
const dialogVisible = ref(false)
const dialogForm = reactive({ sc_course_id: '', sc_student_id: '' })
const courseList = ref([])
const studentList = ref([])

const handleAdd = () => {
  dialogForm.sc_course_id = ''
  dialogForm.sc_student_id = ''
  courseList.value = []
  studentList.value = []
  dialogVisible.value = true
}

const remoteCourse = async (q) => {
  const res = await getCourseAPI({ pageNo: 1, pageSize: 50, cname: q || '' })
  courseList.value = res?.list || []
}

const remoteStudent = async (q) => {
  const res = await getStudentAPI({ pageNo: 1, pageSize: 50, sname: q || '' })
  studentList.value = res?.list || []
}

const handleSubmit = async () => {
  if (!dialogForm.sc_course_id || !dialogForm.sc_student_id) return
  await addChooseAPI({ sc_course_id: dialogForm.sc_course_id, sc_student_id: dialogForm.sc_student_id })
  dialogVisible.value = false
  fetchChooseData()
}
</script>

<style lang="scss" scoped>
.choose-container {
   padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.search-bar {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0 0 18px 0;
  background: none;
  border: none;
  box-shadow: none;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 0;
  margin: 0;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 8px;
}
.search-form .el-input__wrapper,
.search-form .el-button {
  height: 26px !important;
  min-height: 26px !important;
  font-size: 13px;
}
.table-card {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding-top: 6px;
}
.table-card :deep(.el-card__body) {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-card :deep(.el-table) {
  flex: 1 1 auto;
  overflow: auto;
}
.pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
</style>
